package com.dab.springboot.generator.Controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dab.springboot.generator.common.Constants;
import com.dab.springboot.generator.common.R;
import com.dab.springboot.generator.domain.User;
import com.dab.springboot.generator.dto.UserDto;
import com.dab.springboot.generator.mapper.UserMapper;
import com.dab.springboot.generator.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/user")
public class ControllerUser {
    public final UserService userService;
    public final UserMapper UserMapper;

    public ControllerUser(UserService userService, UserMapper userMapper) {
        this.userService = userService;
        this.UserMapper = userMapper;
    }

    @PostMapping
    public boolean save(@RequestBody User user) {
        return userService.saveOrUpdate(user);
    }

//    @PutMapping
//    public boolean update(@RequestBody User user) {
//        return userService.updateById(user);
//    }

    @GetMapping("/kkk")
    public List<User> all() {
        return userService.list();
    }

    //删除
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id) {
        return userService.removeById(id);
    }

    //批量删除
    @PostMapping("/del/batch")
    public boolean deleteBatch(@RequestBody List<Integer> ids) { // [1,2,3]
        return userService.removeByIds(ids);
    }

    @GetMapping("/page")
    public IPage<User> userPage(@RequestParam int pageNum, @RequestParam int pageSize,
                                @RequestParam(defaultValue = "") String username,
                                @RequestParam(defaultValue = "") String email,
                                @RequestParam(defaultValue = "") String address) {
        IPage<User> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();

        lqw.like(Strings.isNotEmpty(username), User::getUsername, username);
        lqw.like(Strings.isNotEmpty(address), User::getAddress, address);
        lqw.like(Strings.isNotEmpty(email), User::getEmail, email);
        lqw.orderByDesc(User::getId);
        return userService.page(page, lqw);
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        //从数据库中查找全部数据
        List<User> list = userService.list();
        //创建Writer工具类，写出磁盘到数据
        ExcelWriter writer = ExcelUtil.getWriter(true);

        //指定别名
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("nickname", "昵称");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("address", "地址");
        writer.addHeaderAlias("createTime", "创建时间");
        writer.addHeaderAlias("avatarUrl", "头像");
        writer.addHeaderAlias("role", "角色");

        //将数据传入excel,使用默认样式
        writer.write(list, true);
        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        //数据流输出数据
        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream, true);
        outputStream.close();
        writer.close();
    }

    /**
     * 导入接口
     *
     * @param file
     */
    @PostMapping("/import")
    public Boolean imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);

        //忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);
        List<User> users = CollUtil.newArrayList();
        for (List<Object> row : list) {
            User user = new User();
            user.setUsername(row.get(1).toString());
//            user.setPassword(row.get(1).toString());
            user.setNickname(row.get(3).toString());
            user.setEmail(row.get(4).toString());
            user.setPhone(row.get(5).toString());
            user.setAddress(row.get(6).toString());
            user.setAvatarUrl(row.get(7).toString());
            users.add(user);
        }

        userService.saveBatch(users);
        return true;
    }

    //登录
    @PostMapping("/login")
    public R login(@RequestBody UserDto userDto) {
        String username = userDto.getUsername();
        String password = userDto.getPassword();
        //判断参数是否为空
        if (Strings.isBlank(username) || Strings.isBlank(password)) {
            return R.error(Constants.C0DE_400, "参数错误");
        }
        UserDto login = userService.login(userDto);
        return R.success(login);
    }
}
